package com.zb777.shuzhilingxi.service.impl;

import com.zb777.shuzhilingxi.Pojo.dto.UserDTO;
import com.zb777.shuzhilingxi.Pojo.dto.UserLoginDTO;
import com.zb777.shuzhilingxi.Pojo.entity.User;
import com.zb777.shuzhilingxi.Pojo.vo.UserVo;
import com.zb777.shuzhilingxi.context.BaseContext;
import com.zb777.shuzhilingxi.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb777.shuzhilingxi.result.Result;
import com.zb777.shuzhilingxi.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public Result register(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (username == null || password == null) {
            return Result.error("用户名或密码不能为空");
        }
        if (username.length() < 3 || username.length() > 20) {
            return Result.error("用户名长度必须在3-20之间");
        }
        if (password.length() < 6 || password.length() > 20) {
            Result.error("密码长度必须在6-20之间");
        }
        boolean exists = lambdaQuery().eq(User::getUsername, username).exists();
        if (exists) {
            return Result.error("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setIsActive(true);
        save(user);
        return Result.success("注册成功");
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            throw new RuntimeException("账号不存在");
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            throw new RuntimeException("密码错误");
        }
        if (!user.getIsActive()) {
            throw new RuntimeException("账号被禁用");
        }
        return user;
    }

    @Override
    public User SelectByUserId(Long userId) {
        User user = lambdaQuery().eq(User::getUserId, userId).one();
        return user;
    }

}
